/**
 * Baidu.com Inc.
 * Copyright (c) 2022 All Rights Reserved.
 */
package guaduation.connection.serialPort;

import guaduation.enums.OrderEnums;
import guaduation.exception.*;
import guaduation.listener.RFIDListener;
import guaduation.utils.HexUtil;
import guaduation.utils.SerialTool;
import guaduation.vo.SerialPortVO;

import java.util.Scanner;

/**
 * @author wangjiajun06
 * @version 1.0
 * @description
 * @date 2022/1/17 10:57 上午
 */
public class RFIDConnection {

    SerialPortVO serialPortVO;
    public void init() throws
            SerialPortParameterFailure,
            NoSuchPort,
            PortInUse,
            NotASerialPort,
            TooManyListeners,
            SerialPortOutputStreamCloseFailure,
            SendDataToSerialPortFailure,
            InterruptedException {

        serialPortVO = SerialTool.openPort("我是dtu的串口", "COM3", 9600);
        serialPortVO.bindListener(new RFIDListener(), 500);
        read();
//        readInput();

    }

    /**
     * 自动读
     * @throws InterruptedException
     * @throws SerialPortOutputStreamCloseFailure
     * @throws SendDataToSerialPortFailure
     */
    private void read() throws
            InterruptedException,
            SerialPortOutputStreamCloseFailure,
            SendDataToSerialPortFailure {
            serialPortVO.sendData(HexUtil.hexStringToByte(OrderEnums.STOP.getOrder()));
        while (true) {
            serialPortVO.sendData(HexUtil.hexStringToByte(OrderEnums.IDENTIFY.getOrder()));
            Thread.sleep(3000);
        }
    }

    /**
     * 手动输入指令序号
     * @throws SerialPortOutputStreamCloseFailure
     * @throws SendDataToSerialPortFailure
     */
    private void readInput() throws SerialPortOutputStreamCloseFailure, SendDataToSerialPortFailure {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            int i = scanner.nextInt();
            System.out.println("输入" + i);
            String order;
            order = OrderEnums.getOrderByIndex(i);
            serialPortVO.sendData(HexUtil.hexStringToByte(order));
        }
    }
}
